<script>
import UInput from "../../uni_modules/uview-ui/components/u--input/u--input.vue";
import { feedback } from '../../api/common/common';

export default {
  name: "qa",
  components: {UInput},
  data() {
    return {
      content: '',
      phone: '',
      loading: false,
      time: 0,
    }
  },
  methods: {
    //格式化时间
    formatDate(date) {
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      let day = date.getDate();
      let hour = date.getHours();
      let minute = date.getMinutes();
      let second = date.getSeconds();
      return [year, month, day].join('-') + ' ' + [hour, minute, second].join(':');
    },
    submit() {
      if (!this.content) {
        uni.showToast({
          title: '请输入问题描述或建议',
          icon: 'none'
        });
        return;
      }
      if (!this.phone) {
        uni.showToast({
          title: '请输入联系电话',
          icon: 'none'
        });
        return;
      }
      if (!/^1[3456789]\d{9}$/.test(this.phone)) {
        uni.showToast({
          title: '手机号格式不正确',
          icon: 'none'
        });
        return;
      }
      this.loading = true;
      feedback({
        content: this.content,
        phone: this.phone,
        time: this.formatDate(new Date()),
      }).then(res => {
        this.loading = false;
        if (res.code === 0) {
          uni.showToast({
            title: '提交成功',
            icon: 'success'
          });
          this.content = '';
          this.phone = '';
        } else {
          uni.showToast({
            title: res.msg,
            icon: 'none'
          });
        }
      }).catch(() => {
        this.loading = false;
        uni.showToast({
          title: '提交失败',
          icon: 'none'
        });
      }).finally(() => {
        this.loading = false;
        // 60秒内不能重复提交
        this.time = 60;
        const timer = setInterval(() => {
          this.time--;
          if (this.time === 0) {
            clearInterval(timer);
          }
        }, 1000);
      });
    },
  }
}
</script>

<template>
  <view>
    <view class="m-title">问题反馈</view>
    <view class="title">问题描述或建议</view>
    <view>
      <u-textarea v-model="content" placeholder="请输入内容" count maxlength="100"></u-textarea>
    </view>
    <view class="title">联系电话</view>
    <view>
      <u-input v-model="phone" placeholder="请输入手机号" count maxlength="11"></u-input>
    </view>
    <view class="btn-wrap">
      <u-button
          type="primary"
          @click="submit"
          :loading="loading"
          loading-text="提交中"
          :disabled="time > 0"
      >
        {{ time > 0 ? `${time}s后重新可再次提交` : '提交' }}
      </u-button>
    </view>
  </view>
</template>

<style scoped lang="scss">
  .m-title{
    text-align: center;
    font-size: 36rpx;
    margin-bottom: 60rpx;
    padding-top: 35px;
    font-weight: bold;
  }
  .title{
    margin-top: 20rpx;
    margin-bottom: 20rpx;
  }
  .btn-wrap{
    margin-top: 40rpx;
    text-align: center;
  }
</style>